package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.hmall.feign.clients.ItemClient;
import com.hmall.feign.clients.UserClient;
import com.hmall.feign.dto.AddressDTO;
import com.hmall.feign.pojo.Item;
import com.hmall.order.constant.StatusOrderPay;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.RequestParams;
import com.hmall.order.service.IOrderDetailService;
import com.hmall.order.service.IOrderLogisticsService;
import com.hmall.order.service.IOrderService;

import com.hmall.order.util.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@Service
@Slf4j
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private UserClient userClient;
    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private IOrderLogisticsService orderLogisticsService;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Override
    public Long createOrder(RequestParams requestParams) {
        //根据itemId查询商品信息
        Item itemDTO = itemClient.getById(requestParams.getItemId());
        //基于商品价格、购买数量计算商品总价：totalFee
        long totalFee = itemDTO.getPrice() * requestParams.getNum(); //总金额


        Order order = new Order();
        Long userId1 = UserUtil.getUserId();
        order.setUserId(userId1);
        // 封装order数据
        order.setStatus(StatusOrderPay.NO_PAY); //设置支付状态为未支付
        order.setTotalFee(totalFee);
        order.setPaymentType(requestParams.getPaymentType());
        Date now = new Date();
        order.setCreateTime(now);
        order.setUpdateTime(now);
        this.save(order);
        //将商品信息、orderId信息封装为OrderDetail对象，写入tb_order_detail表
        log.info("创建订单成功，订单号为：{}", order.getId());

        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(order.getId());
        orderDetail.setItemId(requestParams.getItemId());
        orderDetail.setNum(requestParams.getNum());
        orderDetail.setName(itemDTO.getName());
        orderDetail.setSpec(itemDTO.getSpec());
        orderDetail.setPrice(itemDTO.getPrice());
        orderDetail.setImage(itemDTO.getImage());
        orderDetail.setCreateTime(now);
        orderDetail.setUpdateTime(now);
        orderDetailService.save(orderDetail);

        //根据addressId查询user-service服务，获取地址信息
        Long addressId = requestParams.getAddressId();
        AddressDTO address = userClient.findAddressById(addressId);

        //将地址封装为OrderLogistics对象，写入tb_order_logistics表
        OrderLogistics orderLogistics = new OrderLogistics();
        BeanUtils.copyProperties(address, orderLogistics);
        orderLogistics.setOrderId(order.getId());
        orderLogisticsService.save(orderLogistics);

        //减库存
        try {
            itemClient.updateStock(requestParams.getItemId(), requestParams.getNum());
        } catch (Exception e) {
            e.printStackTrace();
//            throw new RuntimeException("库存不足");
        }

        //发送消息到延时队列中，30分中内进行付款。
        Message orderId = MessageBuilder.withBody((order.getId().toString()).getBytes(StandardCharsets.UTF_8))
                .setHeader("x-delay", 1800000)
                //.setHeader("x-delay",60000*30)  //这里用60s模拟,实际应该是30分钟
                .build();
        rabbitTemplate.convertAndSend("order.direct", "timeOut", orderId);
        log.info("发送消息成功！");

        return order.getId();
    }


}
